package com.xuecheng.ucenter.service.impl;

import com.alibaba.fastjson.JSON;
import com.xuecheng.ucenter.mapper.XcMenuMapper;
import com.xuecheng.ucenter.mapper.XcUserMapper;
import com.xuecheng.ucenter.model.dto.AuthParamsDto;
import com.xuecheng.ucenter.model.dto.XcUserExt;
import com.xuecheng.ucenter.model.po.XcMenu;
import com.xuecheng.ucenter.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
// 实现spring security提供的接口
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    private XcUserMapper xcUserMapper;

    @Autowired
    private XcMenuMapper xcMenuMapper;

    @Autowired
    // 注入spring容器
    private ApplicationContext applicationContext;

    // 自定义UserDetailsService接口，重写loadUserByUsername方法
    // 传入的认证的请求参数就是AuthParamsDto
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        // 将传入的json转成AuthParamsDto对象
        AuthParamsDto authParamsDto = null;
        try {
            // 将请求参数转成AuthParamsDto
            authParamsDto = JSON.parseObject(s, AuthParamsDto.class);
        } catch (Exception e) {
            throw new RuntimeException("请求认证参数不符合要求");
        }

        // 获取认证类型
        String authType = authParamsDto.getAuthType();

        // 根据认证类型从spring容器中取出指定的bean
        String beanName = authType + "_authService";
        AuthService authService = applicationContext.getBean(beanName, AuthService.class);
        // 调用统一的execute方法完成认证
        XcUserExt execute = authService.execute(authParamsDto);

        // 封装xcUserExt用户信息为UserDetails
        return getUserPrincipal(execute); // 根据UserDetails对象生成令牌
    }

    /**
     * 查询用户信息
     *
     * @param xcUser 用户id 主键
     * @return 用户信息
     */
    public UserDetails getUserPrincipal(XcUserExt xcUser) {
        String password = xcUser.getPassword();
        // 权限
        String[] authorities = {"test"};

        // 根据用户id查询用户权限
        List<XcMenu> xcMenus = xcMenuMapper.selectPermissionByUserId(xcUser.getId());
        // 判断是否为空
        if (!xcMenus.isEmpty()) {
            // 将权限集合转成数组使用stream流
            authorities = xcMenus.stream().map(XcMenu::getCode).toArray(String[]::new);

            /*// 原始的方式
            List<String> permissions = new ArrayList<>();
            // 拿到用于的权限标识符
            xcMenus.forEach(xcMenu -> permissions.add(xcMenu.getCode()));
            // 将permissions转成数组
            authorities = permissions.toArray(new String[0]);*/
        }


        // 注意需要把一些敏感数据不能放进去 例如密码之类的
        xcUser.setPassword(null);

        // 将用户的信息转成json
        String userJson = JSON.toJSONString(xcUser);
        return User.withUsername(userJson).password(password).authorities(authorities).build();
    }
}
